//
//  DDStatusCellPictureView.swift
//  SinaMicroBlogSwift2
//
//  Created by dqw on 15/8/3.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

private let DDPictureCellId = "cell"
let DDPictureBrowserNotification = "DDPictureBrowserNotification"
let DDPictureBrowserIndexKey = "DDPictureBrowserIndexKey"
let DDPictureBrowserUrlsKey = "DDPictureBrowserUrlsKey"
class DDStatusCellPictureView: UICollectionView {
    
    let flowLayout = UICollectionViewFlowLayout()
    var status: DDStatus? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    
   override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
    
    configureCollectionView()
        
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }

    private func configureCollectionView() {
        registerClass(DDPictureViewCell.self, forCellWithReuseIdentifier: DDPictureCellId)
        self.dataSource = self
        self.delegate = self
        backgroundColor = UIColor.clearColor()
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        super.sizeThatFits(size)
       return calculatedViewSize()
    }
    private func calculatedViewSize() -> CGSize {
        
        let itemSize = CGSize(width: 90, height: 90)
        flowLayout.itemSize = itemSize
        let colNum = 3
        let pictureNum = status?.pictureUrls?.count ?? 0
        let margin:CGFloat = 10
        var size: CGSize
        
        if pictureNum == 0 {
//            flowLayout.itemSize = CGSizeZero
            return CGSizeZero
        }
        
        if pictureNum == 1 {
            
            let key = status!.pictureUrls![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
//            let image = SDWebImageManager.sharedManager().imageCache.imageFormDiskCacheForKey(key)
            
            size = CGSize(width: 150, height: 120)
            if image != nil {
                size = image.size
            }
            
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width

            flowLayout.itemSize = size
            return size
        }
        
        if pictureNum == 4 {
            
            let W = itemSize.width * CGFloat(2) + margin
            size = CGSize(width: W, height: W)
            return size
            
        }
        
        let rowNum = ((pictureNum - 1) / colNum + 1)
        
        let W = itemSize.width * CGFloat(colNum) +  margin * CGFloat(colNum - 1)
        let H = itemSize.width * CGFloat(rowNum) + margin * CGFloat(rowNum - 1)
        size = CGSize(width: W , height: H)
        
        return size
    }
    
    //MARK: -  计算动画图片的起始frame。因为在这里可以得到该条微博的status。
    func frameOfThumbnailImageInHomeView(indexPath: NSIndexPath) -> CGRect {
        let cell = self.cellForItemAtIndexPath(indexPath)!
        return convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow! )
    }
    
    func frameOfLargeImageInHomeView(IndexPath: NSIndexPath) -> CGRect  {
        let key =  status?.pictureUrls![IndexPath.item].absoluteString
//        let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key)
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        let s = image.size
        let screenH = UIScreen.mainScreen().bounds.height
        let screenW = UIScreen.mainScreen().bounds.width
        let heightS = (s.height / s.width) * screenW
        var y: CGFloat = 0
        if heightS < screenH {
            y = (screenH - heightS) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenW, height: heightS)
    }
}

extension DDStatusCellPictureView: UICollectionViewDataSource, UICollectionViewDelegate
{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(DDPictureCellId, forIndexPath: indexPath) as! DDPictureViewCell
    
        
        cell.imageUrl = status!.pictureUrls![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let dict = [DDPictureBrowserIndexKey: indexPath, DDPictureBrowserUrlsKey: status!.pictureLargeUrls!]
        NSNotificationCenter.defaultCenter().postNotificationName(DDPictureBrowserNotification, object: self, userInfo: dict as [NSObject : AnyObject])
    }
}

private class DDPictureViewCell: UICollectionViewCell {
    
     var imageUrl: NSURL? {
        didSet {
            
            imageV.sd_setImageWithURL(imageUrl)
            gifButton.hidden = imageUrl?.pathExtension != "gif"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addAndLayoutSubviews()
    }
    
    private func addAndLayoutSubviews() {
        contentView.addSubview(imageV)
        imageV.ff_Fill(contentView)
        contentView.addSubview(gifButton)
        gifButton.sizeToFit()
        gifButton.ff_AlignInner(type: ff_AlignType.BottomRight, referView: imageV, size: nil)
        gifButton.hidden = true
//        gifButton.backgroundColor = UIColor.redColor()  
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func configuregifButton() {
        
    }
    
     lazy var imageV: UIImageView = {
     
        let imageView = UIImageView()
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    private lazy var gifButton: UIButton = UIButton(imageName: "timeline_image_gif")

}